
import {Message} from "view-design";

export default function initCanvasSignature(id, options) {
    let self = this;
    this.canvas = document.getElementById(id);
    let obj = {
        canvas: this.canvas,
        context: this.canvas.getContext("2d"),
        isWrite: false, //是否开始
        lastWriteTime: -1,
        lastWriteSpeed: 0,
        lastWriteWidth: 0,
        canvasWidth: 400, //canvas宽高
        canvasHeight: 200,
        isShowBorder: true, //是否显示网格
        bgColor: '#fff', //背景色
        borderWidth: 2, // 网格线宽度
        borderColor: "#fff", //网格颜色
        lastPoint: {}, //
        writeWidth: 2, //基础轨迹宽度
        maxWriteWidth: 30, // 写字模式最大线宽
        minWriteWidth: 1, // 写字模式最小线宽
        writeColor: '#000', // 轨迹颜色
        isWriteName:false //签名模式
    }

    for(let name in options) {
        obj[name] = options[name];
    }

    /**
     * 轨迹宽度
     */
    this.setLineWidth = function() {
        let nowTime = new Date().getTime();
        let diffTime = nowTime - obj.lastWriteTime;
        obj.lastWriteTime = nowTime;
        let returnNum = obj.minWriteWidth + (obj.maxWriteWidth - obj.minWriteWidth) * diffTime / 30;
        if(returnNum < obj.minWriteWidth) {
            returnNum = obj.minWriteWidth;
        } else if(returnNum > obj.maxWriteWidth) {
            returnNum = obj.maxWriteWidth;
        }

        returnNum = returnNum.toFixed(2);
//写字模式和签名模式
        if(obj.isWriteName){
            obj.context.lineWidth = obj.writeWidth;
        }else{
            obj.context.lineWidth = obj.lastWriteWidth = obj.lastWriteWidth / 4 * 3 + returnNum / 4;
        }
    }

    /**
     * 绘制轨迹
     */
    this.writing = function(point) {
        obj.context.beginPath();
        obj.context.moveTo(obj.lastPoint.x, obj.lastPoint.y);
        obj.context.lineTo(point.x, point.y);
        self.setLineWidth();
        obj.context.stroke();
        obj.lastPoint = point;
        obj.context.closePath();
    }

    /**
     * 轨迹样式
     */
    this.writeContextStyle = function() {
        obj.context.beginPath();
        obj.context.strokeStyle = obj.writeColor;
        obj.context.lineCap = 'round';
        obj.context.lineJoin = "round";
    }

    /**
     * 写开始
     */
    this.writeBegin = function(point) {
        obj.isWrite = true;
        obj.lastWriteTime = new Date().getTime();
        obj.lastPoint = point;
        self.writeContextStyle();
    }

    /**
     * 写结束
     */
    this.writeEnd = function() {
        obj.isWrite = false;
    }

    /**
     * 清空画板
     */
    this.canvasClear = function() {
        obj.context.save();
        obj.context.strokeStyle = '#fff';
        obj.context.clearRect(0, 0, obj.canvasWidth, obj.canvasHeight);
        if(obj.isShowBorder && !obj.isWriteName) {
            obj.context.beginPath();
            let size = obj.borderWidth / 2;
//画外面的框
            obj.context.moveTo(size, size);
            obj.context.lineTo(obj.canvasWidth - size, size);
            obj.context.lineTo(obj.canvasWidth - size, obj.canvasHeight - size);
            obj.context.lineTo(size, obj.canvasHeight - size);
            obj.context.closePath();
            obj.context.lineWidth = obj.borderWidth;
            obj.context.strokeStyle = obj.borderColor;
            obj.context.stroke();
//画里面的框
            obj.context.moveTo(0, 0);
            obj.context.lineTo(obj.canvasWidth, obj.canvasHeight);
            obj.context.lineTo(obj.canvasWidth, obj.canvasHeight / 2);
            obj.context.lineTo(obj.canvasWidth, obj.canvasHeight / 2);
            obj.context.lineTo(0, obj.canvasHeight / 2);
            obj.context.lineTo(0, obj.canvasHeight);
            obj.context.lineTo(obj.canvasWidth, 0);
            obj.context.lineTo(obj.canvasWidth / 2, 0);
            obj.context.lineTo(obj.canvasWidth / 2, obj.canvasHeight);
            obj.context.stroke();

        }
        obj.context.restore();
    }

    /**
     * 保存图片 格式base64
     */
    this.saveAsImg = function() {
        let image = new Image();
        image.src = this.canvas.toDataURL("image/png");
        // if(image.src == this.emptyCanvas) {
            // Message.warning(({content: "请先签名", duration: 6, closable: true}))
            // return {base64:image.src,file:base64toFile(image.src)}
            // return;
        // }
       return {base64:image.src,file:base64toFile(image.src)}
    };

    /**
     * 初始化画板
     */
    this.canvasInit = function() {
        this.canvas.width = obj.canvasWidth;
        this.canvas.height = obj.canvasHeight;
        this.emptyCanvas = this.canvas.toDataURL("image/png");
        //defaultImage
    }

    /**======================事件绑定===========================**/

    this.canvas.addEventListener('mousedown', function(e) {
        let point = {
            x: e.offsetX || e.clientX,
            y: e.offsetY || e.clientY
        };
        self.writeBegin(point);
    });

    this.canvas.addEventListener('mouseup', function(e) {
        let point = {
            x: e.offsetX,
            y: e.offsetY
        };
        self.writeEnd(point);
    });

    this.canvas.addEventListener('mouseleave', function(e) {
        let point = {
            x: e.offsetX,
            y: e.offsetY
        };
        self.writeEnd(point);
    });

    this.canvas.addEventListener('mousemove', function(e) {
        if(obj.isWrite) {
            let point = {
                x: e.offsetX,
                y: e.offsetY
            };

            self.writing(point);
        }
    });

//移动端
    this.canvas.addEventListener('touchstart', function(e) {
        let touch = e.targetTouches[0];
        let point = {
            x: touch.pageX || touch.clientX,
            y: touch.pageY || touch.clientY
        };
        self.writeBegin(point);
    });
    this.canvas.addEventListener('touchend', function(e) {
        let touch = e.changedTouches[0];
        let point = {
            x: touch.pageX,
            y: touch.pageY
        };
        self.writeEnd(point);
    });
    this.canvas.addEventListener('touchmove', function(e) {
        let touch = e.targetTouches[0];
        let point = {
            x: touch.pageX,
            y: touch.pageY
        };
        self.writeEnd(point);
    });
    this.canvas.addEventListener('touchmove', function(e) {
        let touch = e.targetTouches[0];
        let point = {
            x: touch.pageX,
            y: touch.pageY
        };
        self.writing(point);
    });

    this.canvasInit();
    this.canvasClear();

    if (obj.defaultImage){
        let imgObj = new Image();
        imgObj.src = obj.defaultImage
        imgObj.onload = function(){
            obj.context.drawImage(this, 0, 0,obj.canvasWidth,obj.canvasHeight);
        }

    }

    this.option = obj;
    obj.control = {
        clearCanvas: self.canvasClear
    };
}


function base64toFile(dataurl, filename = 'file') {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let suffix = mime.split('/')[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
    });
}
